from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from django.core.urlresolvers import reverse

from myadmin import models
from django.contrib.auth.hashers import make_password, check_password

# Create your views here.

# 前台首页
def index(request):

    # 获取所有的一级分类
    data = models.Cates.objects.filter(pid=0)

    # 获取当前一级类下的二级分类
    for x in data:
        x.sub = models.Cates.objects.filter(pid=x.id)


    context = {'data':data}


    '''
    [
        'name':'点心/蛋糕',
            'sub':[
                'name':'点心','goodslist':[
                        goodsobject,goodsobject
                    ],
                'name':'蛋糕','goodslist':[
                        goodsobject,goodsobject
                    ]
                ],
        'name':'饼干/膨化','sub':['name':'饼干','goodslist':[goodsobject,goodsobject],'name':'膨化','goodslist':[goodsobject,goodsobject]]
    ]
    '''
    return render(request,'myhome/index.html',context)

def goodslist(request):
    # 接收id 
    cid = request.GET.get('cid')
    # 获取当前二级分类的对象
    ob = models.Cates.objects.get(id=cid)

    ob.goodslist = models.Goods.objects.filter(cateid=ob).order_by(request.GET.get('orderby','id'))


    # 分配数据
    context = {'data':ob}

    # 加载模板
    return render(request,'myhome/list.html',context)

# 详情
def goodsinfo(request):
    # 接收商品id
    gid = request.GET.get('gid')

    # 根据商品id获取对象
    ob = models.Goods.objects.get(id=gid)

    # 分配数据
    context = {'data':ob}
    # 加载模板
    return render(request,'myhome/info.html',context)

# 加入购物车
def cartadd(request):
    # 商品id  商品数量 用户id
    goods = models.Goods.objects.get(id=request.GET.get('gid'))
    user = models.Users.objects.get(id=request.session['VipUser']['uid'])
    num = int(request.GET.get('num'))


    # 检查当前的商品是否已经存在购物车
    res = models.Cart.objects.filter(goodsid=goods).filter(uid=user)

    if res.count():
        #已存在,更新数量
        for v in res:
            v.num += num
            v.save()
    else:
        # 添加到数据库
        ob = models.Cart(goodsid=goods,uid=user,num=num)
        ob.save()


    return JsonResponse({'error':0,'msg':'加入购物成功'})

# 购物车列表页
def cartindex(request):
    # 获取当前用户的购物车数据
    data = models.Cart.objects.filter(uid=request.session['VipUser']['uid'])

    # 分配数据
    context = {'data':data}

    # 加载页面
    return render(request,'myhome/cart.html',context)

# 购物车商品数量 修改
def cartedit(request):
    # 购物车id  数量
    cartid = request.GET.get('cartid')
    num = request.GET.get('num')

    # 获取购物车对象
    ob = models.Cart.objects.get(id=cartid)
    ob.num = int(num)
    ob.save()

    # 运算小计价格
    totalprice = ob.num*ob.goodsid.price


    return JsonResponse({'error':0,'msg':'修改成功','totalprice':"{:.2f}".format(totalprice)})
    
# 购物车商品 删除
def cartdel(request):

    # 购物车id
    cid = request.GET.get('cid')
    # 获取购物车对象
    ob = models.Cart.objects.get(id=cid)
    print(ob)
    ob.delete()

    return JsonResponse({'error':0,'msg':'删除成功'})


# 订单确认
def orderconfirm(request):

    # 接收 cartids
    cartids = eval(request.GET.get('cartids'))
    
    # 获取对应的购物车数据
    data = models.Cart.objects.filter(id__in=cartids)

    # 获取所有的一级城市数据
    citys = models.Citys.objects.filter(level = 1)

    # # 获取当前用户
    # user = models.Users.objects.get(id=request.session['VipUser']['uid'])

    # # 获取当前用户的默认地址
    # useraddres = user.address_set.get(isChecked=True) 
    # # print(res)
    # []
    # 分配数据
    context = {'data':data,'citys':citys}

    # 加载模板
    return render(request,'myhome/confirm.html',context)



# 订单创建
def ordercreate(request):
    # 获取提交的订单数据
    data = request.POST.dict()
    data.pop('csrfmiddlewaretoken')
    # {'cartids': '["4","5"]', 'buytype': 'zhifubao', 'wl': 'yunda', 'addressid': '3'}

    # 添加订单
    # 获取用户对象
    user = models.Users.objects.get(id=request.session['VipUser']['uid'])
    # 获取地址信息
    addr = models.Address.objects.get(id=data['addressid'])
    sheng = models.Citys.objects.get(id=addr.sheng).name
    shi = models.Citys.objects.get(id=addr.shi).name
    xian = models.Citys.objects.get(id=addr.xian).name
    shdz = sheng+shi+xian+addr.info

    # 总价计算
    totalprice = 0
    cart = models.Cart.objects.filter(id__in=eval(data['cartids']))
    for x in cart:
        totalprice += x.num*x.goodsid.price


    # 准备订单数据
    orderdata={'uid':user,'shr':addr.shr,'shdh':addr.shdh,'shdz':shdz,'buytype':data['buytype'],'wl':data['wl']}
    orderdata['totalprice'] = totalprice
    # {'totalprice': 259.2, 'shdh': '111111', 'shdz': '山西省晋城市阳城县111', 'buytype': 'zhifubao', 'uid': <Users: Users object>, 'shr': '李四', 'wl': 'yunda'}

    # 创建订单
    order = models.Order(**orderdata)
    order.save()

    # 生成订单详情
    for x in cart:
        odinfo = models.OrderInfo()
        odinfo.orderid = order
        odinfo.goodsid = x.goodsid.id
        odinfo.title = x.goodsid.title
        odinfo.pic_url = x.goodsid.pic_url
        odinfo.price = x.goodsid.price
        odinfo.num = x.num
        # 添加到订单详情
        odinfo.save()
        # 删除购物车中已经下单的商品
        x.delete()


    # 跳转到支付页面

    return HttpResponse('<script>alert("订单创建成功,请前往支付");location.href="/order/buy/?orderid='+str(order.id)+'"</script>')

# 订单支付页面
def orderbuy(request):
    # 订单号
    orderid = request.GET.get('orderid')
    print(orderid)
    
    return HttpResponse('订单支付')



# 我的订单
def myinfo_order(request):
    # 获取当前用户
    user = models.Users.objects.get(id=request.session['VipUser']['uid'])

    # 分配数据
    context = {'user':user}

    # 加载模板
    return render(request,'myhome/myinfo/order.html',context)

# 订单删除
def myinfo_order_del(request):
    # 获取当前订单
    user = models.Order.objects.get(id=request.GET.get('id'))
    user.delete()

    # 加载模板
    return HttpResponse('<script>alert("删除成功");location.href="'+reverse('myhome_myinfo_order')+'"</script>')

# 我的收货地址
def myinfo_address(request):
    # 获取所有的一级城市数据
    citys = models.Citys.objects.filter(level = 1)

    # 分配数据
    context = {'citys':citys}

    # 加载模板
    return render(request,'myhome/myinfo/address.html',context)

# 删除收货地址
def myinfo_address_del(request):
    addr = models.Address.objects.get(id=request.GET.get('id'))
    addr.delete()
    return JsonResponse({'error':0, 'data':'删除成功'})

# 设置默认收货地址
def myinfo_address_default(request):
    address = models.Address.objects.all()
    for x in address:
        x.isChecked = 0
        x.save()
    addr = models.Address.objects.get(id=request.GET.get('id'))
    addr.isChecked = 1
    addr.save()
    return JsonResponse({'error':0, 'data':'设置成功'})

# 个人信息
def myinfo_information(request):
    # 获取当前用户
    user = models.Users.objects.get(id=request.session['VipUser']['uid'])
    # 分配数据
    context = {'user': user}
    # 加载模板
    return render(request,'myhome/myinfo/information.html',context)

# 收货地址获取
def addresslist(request):
    try:
        # 获取当前用户的所有收货地址
        data = models.Address.objects.filter(uid=request.session['VipUser']['uid']).values()

        for x in data:
            x['sheng'] = models.Citys.objects.get(id=x['sheng']).name
            x['shi'] = models.Citys.objects.get(id=x['shi']).name
            x['xian'] = models.Citys.objects.get(id=x['xian']).name

        #返回数据
        return JsonResponse({'error':0,'data':list(data)},safe=False)
    except:
        return JsonResponse({'error':1,'msg':'当前用户没有收货地址'})



# 收货地址添加
def addressadd(request):
    
    # 接收地址信息
    data = request.GET.dict()

    # 获取当前用户对象
    data['uid'] = models.Users.objects.get(id=request.session['VipUser']['uid'])

    # 进行数据存储
    ob = models.Address(**data)
    ob.save()

    # 返回结果
    return JsonResponse({'aa':1})

# 返回城市数据
def getcitys(request):
    
    # 根据id获取下一级的城市数据,返回json
    data = models.Citys.objects.filter(upid=request.GET.get('id')).values()

    # 解析json  返回
    return JsonResponse(list(data),safe=False)


def login(request):
    nextpath = request.GET.get('nextpath','/')
    args = eval(request.GET.get('args','{}'))
    a = ''
    for k,v in args.items():
        a+= '&'+k+'='+v
    nexturl = nextpath+'?'+a


    if request.method == 'GET':
        return render(request,'myhome/login.html')

    else:
        # 执行登录
        try:
            # 先根据手机号获取用户,
            ob = models.Users.objects.get(phone=request.POST['phone'])
            # 在对比密码是否正确
            res = check_password(request.POST['password'],ob.password)
            if res:
                # 用户名和密码都正确
                # 在session中存入登录凭证
                request.session['VipUser'] = {'username':ob.username,'phone':ob.phone,'uid':ob.id,'pic_url':ob.pic_url}
                # 跳转到首页
                return HttpResponse('<script>alert("登录成功");location.href="'+nexturl+'"</script>')
            else:
                # 密码错误
                pass
        except:
            pass
            # 用户名不存在
        
        return HttpResponse('<script>alert("用户名或密码错误");location.href="'+reverse('myhome_login')+'"</script>')


def logout(request):

    del request.session['VipUser']

    return HttpResponse('<script>alert("退出登录");location.href="/";</script>')

def register(request):
    if request.method == 'GET':
        return render(request,'myhome/register.html')
    else:
        try:
            # 验证手机号和验证码是否和session中一致
            if request.POST['phone'] != request.session['msgcode']['phone'] or request.POST['code'] != request.session['msgcode']['code']:
                return HttpResponse('<script>alert("注册失败,验证码不正确");location.href="'+reverse('myhome_register')+'"</script>')
            
            # 密码加密
            password  = make_password(request.POST['password'], None, 'pbkdf2_sha256')
            # 生成随机的用户名
            username = 'user'+str(request.POST['phone'])
            data = {'username':username,'phone':request.POST['phone'],'password':password}
            
            # 执行注册
            ob = models.Users(**data)
            ob.save()
            # 跳转登录页面
            return HttpResponse('<script>alert("注册成功.请登录");location.href="'+reverse('myhome_login')+'"</script>')
        except:
            return HttpResponse('<script>alert("注册失败");location.href="'+reverse('myhome_register')+'"</script>')



# 验证手机号
def checkphone(request):
    # 接受手机号
    phone = request.GET.get('phone')
    # 到数据库查询
    num = models.Users.objects.filter(phone=phone).count()

    if num:
        return JsonResponse({'error':1,'msg':'手机号码已存在'})
    else:
        return JsonResponse({'error':0,'msg':'手机号码不存在'})


# 手机短信验证码发送
def sendmsg(request):
    #接口类型：互亿无线触发短信接口，支持发送验证码短信、订单通知短信等。
    #账户注册：请通过该地址开通账户http://user.ihuyi.com/register.html
    #注意事项：
    #（1）调试期间，请用默认的模板进行测试，默认模板详见接口文档；
    #（2）请使用 用户名 及 APIkey来调用接口，APIkey在会员中心可以获取；
    #（3）该代码仅供接入互亿无线短信接口参考使用，客户可根据实际需要自行编写；
      
    # import urllib2
    import urllib
    import urllib.request
    import json
    import random
    #用户名 查看用户名请登录用户中心->验证码、通知短信->帐户及签名设置->APIID
    account  = "C08111534" 
    #密码 查看密码请登录用户中心->验证码、通知短信->帐户及签名设置->APIKEY
    password = "4f2db76276519dd8ecfe1c97bd23a9bb"
    # 接受注册页面提供的手机号
    mobile = request.GET.get('phone')
    # 随机验证码
    code = str(random.randint(10000,99999))
    print(code)
    # 把验证码存入session
    request.session['msgcode'] = {'phone':mobile,'code':code}
    # text = "您的验证码是："+code+"。请不要把验证码泄露给其他人。"
    # data = {'account': account, 'password' : password, 'content': text, 'mobile':mobile,'format':'json' }
    # # 发起 请求
    # req = urllib.request.urlopen(
    #     url= 'http://106.ihuyi.com/webservice/sms.php?method=Submit',
    #     data= urllib.parse.urlencode(data).encode('utf-8')
    # )
    # # 获取响应内容
    # content =req.read()
    # # 解析结果
    # res = json.loads(content.decode('utf-8'))
    # print(res)
    return HttpResponse('aa')






